package com.redstar.HappyRefresh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redstar.HappyRefresh.mapper.RoleMapper;
import com.redstar.HappyRefresh.pojo.*;
import com.redstar.HappyRefresh.service.PermissionService;
import com.redstar.HappyRefresh.service.RolePermissionService;
import com.redstar.HappyRefresh.service.RoleService;
import com.redstar.HappyRefresh.service.UserRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService { // 角色服务

    @Autowired
    private PermissionService permissionService; // 权限
    @Autowired
    private RolePermissionService rolePermissionService; // 角色权限
    @Autowired
    private UserRoleService userRoleService; // 用户角色

    @Override
    public List<Tree> tree() {
        // 将所有的权限取出封装为Tree对象，以树形结构的方式存储在List集合中
        List<Tree> trees = permissionService.list().stream().map(permission -> {
            Tree tree = new Tree(); // 将permission封装成tree对象
            BeanUtils.copyProperties(permission, tree);
            tree.setTitle(permission.getName());
            tree.setSpread(true); // 默认展开
            return tree;
        }).collect(Collectors.toList());
        // 找到根节点
        List<Tree> parent = trees.stream().filter(tree -> tree.getPId().compareTo(0L) == 0).collect(Collectors.toList());
        for (Tree tree : parent) { // 将所用的tree对象封装成树形结构
            findChildren(tree, trees);
        }
        return parent;
    }

    @Override
    @Transactional
    public String removeRole(String id) { // 删除角色，同时删除角色权限和用户角色
        try {
            // 根据角色id删除角色权限
            rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, id));
            // 根据角色id删除角色
            baseMapper.deleteById(id);
            // 根据角色id删除删除用户角色
            userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId, id));
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); // 发生错误，回滚事务
            return e.getMessage();
        }
        return "success";
    }

    @Override
    @Transactional
    public String gavePermission(AuthorityVO authorityVO) { // 为角色重新分配权限
        // AuthorityVO类的属性为角色id(Integer rid)，权限id(Integer[] pid)
        try {
            Integer rid = authorityVO.getRid();
            // 删除角色之前的权限
            rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, rid));
            List<RolePermission> list = new ArrayList<>();
            for (Integer pId : authorityVO.getPid()) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(rid);
                rolePermission.setPermissionId(pId);
                list.add(rolePermission);
            }
            // 为角色分配新的权限，批量插入
            rolePermissionService.saveBatch(list);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); // 发生错误，回滚事务
            return e.getMessage();
        }
        return "success";
    }

    @Override
    @Transactional
    public String gaveRole(AssignRoleVO assignRoleVO) { // 为用户重新分配角色
        // AuthorityVO类的属性为用户id(Long uId)，角色id(Long[] rId)
        try {
            Long uId = assignRoleVO.getUId(); // 获取被分配角色的用户id
            // 删除用户之前的角色
            userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, uId));
            List<UserRole> userRoles = new ArrayList<>();
            for (Long id : assignRoleVO.getRId()) {
                UserRole userRole = new UserRole();
                userRole.setUserId(uId);
                userRole.setRoleId(id);
                userRoles.add(userRole);
            }
           // 为用户分配新的角色，批量插入
            userRoleService.saveBatch(userRoles);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); // 发生错误，回滚事务
            return e.getMessage();
        }
        return "success";
    }

    private Tree findChildren(Tree datum, List<Tree> trees) { // 找到指定根节点的全部子节点，构造了一颗完整的树结构
        datum.setChildren(new ArrayList<>());
        for (Tree tree : trees) {
            if (tree.getPId().compareTo(datum.getId()) == 0) {
                // 递归调用
                datum.getChildren().add(findChildren(tree, trees));
            }
        }
        return datum;
    }
}
